package com.zr0726.news.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zr0726.news.po.GiteeRequest;
import com.zr0726.news.po.GiteeUser;

import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Auther Jack
 * @Date 2020/7/29
 */
@Component
public class GiteeUserServiceImpl {
    public String getAccess(GiteeRequest accessToken) {
        MediaType mediaType= MediaType.get("application/json; charset=utf-8");

        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(mediaType,JSON.toJSONString(accessToken));
        Request request = new Request.Builder()
                .url("https://gitee.com/oauth/token?")
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {

            String string = response.body().string();
            JSONObject obj =  JSONObject.parseObject(string );

                String access_token = obj.getString("access_token");
            System.out.println(access_token);
            return access_token;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    public GiteeUser getGiteeUser(String Token)  {
        OkHttpClient client = new OkHttpClient();


        Request request = new Request.Builder()
                .url("https://gitee.com/api/v5/user?access_token=" + Token)
                .build();

        try {
            Response response = client.newCall(request).execute();

            String string = response.body().string();
            GiteeUser giteeUser = JSON.parseObject(string, GiteeUser.class);
            return giteeUser;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


}
